package com.asiainfo.indb.view;

import com.asiainfo.indb.PanelUtil;
import com.asiainfo.indb.model.FileGather;
import com.asiainfo.indb.model.InDbGather;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.*;

/**
 * inDb面板基类
 *
 * @author zym
 * @date 2019-10-17 11:03
 */
public abstract class BaseInDbPanel extends JPanel implements InDbPanel {

    /**
     * 当前面板的父面板
     */
    private InDbPanel parentPanel;

    public BaseInDbPanel(InDbPanel parentPanel) {
        this.parentPanel = parentPanel;

        // 缓存本面板
        cachePanel(this);

        // 渲染面板
        render();

        // 刷新重绘
        validate();
        repaint();
    }

    @Override
    public InDbPanel getParentPanel() {
        return parentPanel;
    }

    @Override
    public void cachePanel(InDbPanel inDbPanel) {
        if (getParentPanel() != null) {
            getParentPanel().cachePanel(inDbPanel);
        }
    }

    @Override
    public <T extends InDbPanel> T getCachedPanel(Class<T> panelCls) {
        if (getParentPanel() != null) {
            return getParentPanel().getCachedPanel(panelCls);
        }

        return null;
    }

    @Override
    public Container getTopContainer() {
        if (getParentPanel() != null) {
            return getParentPanel().getTopContainer();
        }

        return this;
    }

    @Override
    public InDbGather gather() {
        return null;
    }

    @Override
    public void initByFile(FileGather gather) {

    }

    /**
     * 获取当前面板的高度
     *
     * @return 高度值
     */
    protected int getPanelHeight(JPanel mainPanel) {
        // 用内部面板的高度，加上边框的高度
        Insets mainInset = mainPanel.getInsets();
        Insets panelInset = getInsets();
        return mainPanel.getPreferredSize().height + mainInset.top + panelInset.top + mainInset.bottom + panelInset.bottom;
    }

    /**
     * 校验和设置
     *
     * @param desc   描述
     * @param field  输入框
     * @param key    收集的key值
     * @param gather 收集器
     * @return 是否成功收集
     */
    protected boolean checkAndSetField(String desc, JTextField field, String key, InDbGather gather) {
        if (gather != null && field != null && StringUtils.isNotBlank(field.getText())) {
            gather.put(key, field.getText());
            return true;
        }

        PanelUtil.alert(getTopContainer(), desc);
        if (field != null) {
            field.requestFocus();
        }

        return false;
    }

    /**
     * 初始化输入框值
     *
     * @param label  label
     * @param field  input
     * @param gather 值
     */
    protected void initField(String label, JTextField field, InDbGather gather) {
        if (StringUtils.isNotBlank(label) && field != null && gather != null) {
            String value = gather.get(label);
            if (StringUtils.isNotBlank(value)) {
                field.setText(value);
                field.setForeground(Color.BLACK);
            }
        }
    }
}